/**
 * Description:一些注释<br/>
 * CreateTime:2019-03-26<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
package cn.cnsy123.bookwebsiteserver.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import cn.cnsy123.bookwebsiteserver.cache.UserCacheInfo;
import cn.cnsy123.bookwebsiteserver.constant.CacheConstant;

/**
 * Description:用户登录状态检测<br/>
 * CreateTime:2019-03-26<br/>
 * Creater: yangpengfei360@126.com <br/>
 * @author yangpengfei
 */
@WebFilter(filterName = "userFilter",urlPatterns = "/*")
@Order(value = 5)
public class UserFilter implements Filter {
    
    
    private static final Logger logger = LoggerFactory.getLogger(UserFilter.class);
    /**
     * 登陆页面请求
     */
    private static final String LOGIN_PAGE_ADDR = "/loginPage";
    /**
     * 验证码请求
     */
    private static final String IMG_VERTIFY_CODE = "/kaptcha";
    private static final String IMG_VALIDATE_REQUEST = "/imgCode/validate";
    
    /**
     * 登录请求
     */
    private static final String LOGIN_REQUEST = "/login";
    

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
            throws IOException, ServletException {
        
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;
        UserCacheInfo userCacheInfo = (UserCacheInfo)request.getSession().getAttribute(CacheConstant.SESSION_USER);
        String realPath = request.getServletPath();
        logger.info("请求地址:{}",realPath);
        //判断不是登陆页面
        if(!LOGIN_PAGE_ADDR.equals(realPath) 
                //判断不是验证码请求
                && !IMG_VERTIFY_CODE.equals(realPath)
                && !IMG_VALIDATE_REQUEST.equals(realPath)
                //判断不是登录信息
                && !LOGIN_REQUEST.equals(realPath)
                //判断不是静态资源
                && !checkStaticResource(realPath)
                //判断用户缓存为空
                && userCacheInfo == null) {
            
            logger.error("请求携带用户信息为空，将跳转到【登录】页面");
            PrintWriter writer = null;
            try {
                writer = response.getWriter();
                writer.println("<script type='text/javascript'>window.top.location.href = '"+LOGIN_PAGE_ADDR+"?status=loginTimeOut';</script>");
                writer.flush();
            }catch (Exception e) {
                logger.error("跳转页面执行出错，请求错误",e);
            }finally {
                if(writer != null) {
                    writer.close();
                }
            }
            return;
        }
        //其他情况放行
        chain.doFilter(request, response);

    }

    /**
     * Description:检查路径是否为静态资源<br/>
     * CreateTime:2019-03-27<br/>
     * Creater: yangpengfei360@126.com <br/>
     * @author yangpengfei
     * @param realPath
     * @return
     */
    private boolean checkStaticResource(String realPath) {
        
        if(realPath.startsWith("/css") || realPath.startsWith("/js") || realPath.startsWith("/img")) {
            return true;
        }
        
        return false;
    }

}
